const detect = require('detect-port-alt'),
  prompts = require('prompts'),
  chalk = require('chalk'),
  isRoot = require('is-root'),
  clearConsole = require('./clearConsole');

// 是否处于终端模式 -> 针对于 stdout 是否在终端模式；如果输出重定向了或者处于CI模式，则值为 undefined
const isInteractive = process.stdout.isTTY

function choosePort(host, defaultPort) {
  return detect(defaultPort, host)
    .then(port =>
      new Promise(resolve => {
        // 端口号并未被占用
        if (port === defaultPort) {
          resolve(port)
        } else {
          const message =
            process.platform !== 'win32' && defaultPort < 1024 && !isRoot()
              ? `Admin permissions are required to run a server on a port below 1024.`
              : `Something is already running on port ${defaultPort}.`;
          if (isInteractive) {
            clearConsole()
            // 确认是否需要更换端口
            const question = {
              type: 'confirm',
              name: 'shouldChangePort',
              message:
                chalk.yellow(message) + '\n\nWould you like to run the app on another port instead?',
              initial: true,
            };
            prompts(question).then(answer => {
              if (answer.shouldChangePort) {
                resolve(port);
              } else {
                resolve(null);
              }
            });
          } else {
            console.log(chalk.red(message));
            resolve(null)
          }
        }
      })
    )
    .catch(err => {
      throw new Error(
        chalk.red(`Could not find an open port at ${chalk.bold(host)}.`) +
        '\n' +
        ('Network error message: ' + err.message || err) +
        '\n'
      );
    })
}

module.exports = choosePort